package org.thanos.demo.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thanos.demo.service.DemoService;


@Slf4j
@Component
@ChannelHandler.Sharable
public class DemoHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    private DemoService demoService;

    // 读取数据
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        demoService.hello(ctx, msg);
    }

    // 数据读取之前的处理
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        ctx.channel().read();
    }


    // 数据读取完毕的处理
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        log.info("服务端读取数据完毕");
        ctx.channel().read();
    }

    // 出现异常的处理
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.info(cause.getMessage(), cause);
        log.info("server 读取数据出现异常");
        ctx.close();
    }


}
